package cn.springaidemo.controller;

import cn.springaidemo.config.CommentAi;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * <h3>SpringAiDemo</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-04-14 16:22:25
 */
@CrossOrigin(origins = "*")
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai/")
public class ChatController {
    private final CommentAi commentai;

    /**
     * 整体返回
     */
    @GetMapping(value = "chat")
    public String chat(@RequestParam String msg) throws NoApiKeyException, InputRequiredException {
        try {
            GenerationResult result = commentai.callWithMessage(msg);
            return result.getOutput().getChoices().get(0).getMessage().getContent();
        } catch (Exception e) {
            e.printStackTrace();
            return "出错了，请稍后重试~";
        }
    }
    /**
     * 流式返回
     */
    @GetMapping("/chatLiu")
    public SseEmitter chatLiu(@RequestParam String msg) {
        SseEmitter emitter = new SseEmitter(0L); // 不设置超时

        new Thread(() -> {
            try {
                Generation gen = new Generation();
                GenerationParam param =commentai.buildParam(msg, true); // 流式
                Flowable<GenerationResult> flowable = gen.streamCall(param);

                flowable.blockingForEach(result -> {
                    String content = result.getOutput()
                            .getChoices()
                            .get(0)
                            .getMessage()
                            .getContent();
                    try {
                        emitter.send(content);
                    } catch (Exception e) {
                        emitter.completeWithError(e);
                    }
                });
                emitter.send(SseEmitter.event().data("[DONE]"));
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }
}
